import ArticleItem from '@/components/ArticleItem'
import NavBar from '@/components/NavBar'
import { RootState } from '@/store'
import { clearSearchResult, getSearchResult } from '@/store/action/search'
import { InfiniteScroll } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useLocation } from 'react-router'
import styles from './index.module.scss'

export default function SearchResult() {
  const { search } = useLocation()
  // MDN文档：https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams
  const searchParams = new URLSearchParams(search)
  // 获取 URL 的查询参数 q 的值
  const q = searchParams.get('q') || ''

  const dispatch = useDispatch()

  // console.log('获取查询参数q的值', q)
  // useEffect(() => {
  //   dispatch(getSearchResult({ q: q }))
  // }, [q, dispatch])

  //组件卸载时清空搜索结果
  useEffect(() => {
    return () => {
      dispatch(clearSearchResult())
    }
  }, [dispatch])

  const { results } = useSelector((state: RootState) => state.search)

  const [hasMore, setHasMore] = useState(true)
  const currentPage = useRef(0)
  const loadMore = async () => {
    currentPage.current = currentPage.current + 1
    try {
      await dispatch(
        getSearchResult({ q: q, page: currentPage.current, per_page: 10 })
      )
    } catch (error) {
      console.log('没有更多页面了', error)
      setHasMore(false)
    }
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {results.map((item) => (
          <ArticleItem key={item.art_id} article={item} />
        ))}
        {/* 无限滚动 因为开始加载这个组件就会触发，所以副作用的就不用了 */}
        <InfiniteScroll hasMore={hasMore} loadMore={loadMore}></InfiniteScroll>
      </div>
    </div>
  )
}
